<template>
  <div class="h-full flex flex-col overflow-auto">
    <a-form class="flex-1 overflow-hidden flex" :model="registerState" :label-col="{ style: { width: '80px' } }">
      <a-card class="w-3/5 h-full" :body-style="{ height: '100%' }">
        <div class="flex flex-col overflow-hidden">
          <BaseTitle title="伤病员信息" class="!pr-0" />
          <div class="overflow-auto mt-3">
            <PatientInfoForm
              ref="patientInfoForm"
              v-model:value="patientState"
              form-class="pr-1.5"
              item-class="w-1/3"
              :exclude-item="['收费标准']"
              patient-type="普通加预约患者"
              :show-divider-bot-info="false"
              @loaded="patientInfoLoading = false"
              @scan-code="onScanCode"
            />
          </div>
        </div>
        <div v-if="systemConfig.isHistoryList" class="mt-5">
          <BaseTitle title="历史就诊" class="!pr-0" />
          <BaseTable
            bordered
            column-code="000283"
            :exclude-columns="['yqmc', 'jytime', 'ghf', 'je']"
            :loading="loading"
            :scroll="{ x: 1200 }"
            :height="360"
            :data-source="tableData"
            :pagination="false"
          >
            <template #bodyCell="{ column, index }">
              <template v-if="column.dataIndex == 'xh'">
                {{ index + 1 }}
              </template>
            </template>
          </BaseTable>
        </div>
      </a-card>
      <div class="ml-2 w-2/5 h-full overflow-auto flex flex-col">
        <a-card class="flex-1">
          <BaseTitle title="登记" class="" />
          <div class="flex flex-wrap 2xl:mt-4 mt-1">
            <a-form-item label="类别" class="w-1/3" required>
              <SelectRegistType v-model:value="registerState.ghlbid" :disabled="!!registerState.empId" class="w-full" @change="onSelectCategory" />
            </a-form-item>
            <a-form-item label="科室" class="w-1/3 pl-2" required>
              <a-select
                v-model:value="registerState.ksdm"
                :disabled="!!registerState.empId"
                placeholder="请选择"
                :options="departmentList"
                :field-names="{ label: 'ksmc', value: 'ksdm' }"
                @select="onSelectDepartment"
              />
            </a-form-item>
            <a-form-item class="w-1/3 pl-12">
              <a-radio-group v-model:value="registerState.czfz">
                <a-radio :value="0">初诊</a-radio>
                <a-radio :value="1">复诊</a-radio>
              </a-radio-group>
            </a-form-item>
          </div>
          <!-- 选择医生 -->
          <a-carousel arrows class="w-full mb-2" :dots="false" :infinite="false">
            <template #prevArrow>
              <LeftOutlined class="!left-4 !text-base !text-gray-400 !bg-slate-100 z-10 rounded" />
            </template>
            <template #nextArrow>
              <RightOutlined class="!right-4 !text-base !text-gray-400 !bg-slate-100 z-10 rounded" />
            </template>
            <div v-for="(doctorChunk, index) in doctorList" :key="index">
              <CheckTags v-model:value="registerState.empId" tag-key="empId" :data-source="doctorChunk">
                <template #renderItem="{ item }"> {{ item.empName }}{{ item?.numberQuantityLimit }}</template>
              </CheckTags>
            </div>
            <div v-if="doctorList.length === 0" class="w-full h-12 text-disabled !flex items-center">暂无医生</div>
          </a-carousel>
          <a-form-item label="挂号备注" class="w-full mt-2">
            <a-textarea v-model:value="registerState.memo" :rows="3" placeholder="请输入" />
          </a-form-item>
        </a-card>
        <a-card class="mt-2">
          <div class="text-right mr-2 mb-2">
            <a-button class="ml-2 w-28" size="large" @click="onReset">重置</a-button>
            <a-button type="primary" class="ml-2 w-28" size="large" :loading="chargeLoading" :disabled="!isCompleted" @click="savePatientInfo"> 登记 </a-button>
          </div>
        </a-card>
      </div>
    </a-form>

    <SignModal v-model:open="signOpen" :row-data="rowData" @success="onSuccessSignIn" />
  </div>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter, useRoute } from 'vue-router'
import { chunk } from 'lodash-es'
import { LeftOutlined, RightOutlined } from '@ant-design/icons-vue'
import { post, get } from '@/utils/request'
import CheckTags from '@/components/CheckTags'
import { getSystemConfig } from '@/utils/systemConfig'
import cofirmModal from '@/utils/confirm'
import useAppStore from '@/store/app'
// import CouponCard from '@/components/CouponCard'
import SignModal from '@/components/SignModal'
import SelectRegistType from '@/components/SelectRegistType'

// const userInfoStore = useStore()
const appStore = useAppStore()
const router = useRouter()

const patientInfoLoading = ref(true)
const chargeLoading = ref(false)
const signOpen = ref(false)
const patientInfoForm = ref(null)

const patientState = ref({})
const registerState = ref({ ghlbid: null, czfz: 0, xxkf: false, blbf: false }) // czfz: 0,
const rowData = ref({})

watch(
  () => patientState.value?.brId,
  () => {
    if (patientState.value.yylsh) {
      router.push({
        path: '/out-registration/register',
        query: { ...route.query, id: patientState.value.brId, status: '1' }
      })
      setTimeout(() => getPatientInfo(), 300)
    }
    getData()
  }
)

const { loading, tableData, getData } = useTable({
  // url: '/outp/mzdj/getPatientHistoryRegistrationInformationList',
  url: getSystemConfig('IS_HIS_CONNECTIVITY_PATIENT') === '1' ? '/outp/mzdj/getMedicalHistoryList' : '/outp/mzdj/getPatientHistoryRegistrationInformationList',

  formatParams: () => {
    return {
      brId: patientState.value?.brId,
      br_id: patientState.value?.brId
    }
  }
})

const onSelectCategory = (value, option) => {
  registerState.value.ghlbid = value
  registerState.value.ghlb = option.label
  registerState.value.empId = ''
  registerState.value.empName = ''
  getDoctorList(false)
}

const onSelectDepartment = (value) => {
  registerState.value.oldKsdm = value
  registerState.value.ksdms = [value]
  registerState.value.ksdm = value
  getDoctorList()
}

// 获取科室
const departmentList = ref([])
const getDepartmentList = async () => {
  const { code, data } = await post('/outp/mzdj/getDeptInfoList', { sfylks: '0' })
  if (code !== 0) return
  departmentList.value = data
  getDoctorList()
}
//获取医生
const doctorList = ref([[]])
const getDoctorList = async (isDelete = true) => {
  const params = {
    ksdm: registerState.value.ksdm,
    ghlbid: registerState.value.ghlbid
  }
  if (patientState.value.yylsh && isDelete) {
    delete params.ghlbid
  }
  const { code, data = [] } = await post('/outp/mzdj/getSchedulingDocterList', params)
  if (code !== 0) return
  doctorList.value = chunk(data, 10)
  // registerState.value.empId = patientState.value.empId
  if (doctorList.value.length > 0) {
    const doctorItem = doctorList.value.flat().find((i) => {
      return i.empId === patientState.value.empId
    })
    if (doctorItem) {
      registerState.value.empId = doctorItem ? doctorItem.empId : ''
      registerState.value.ghlbid = doctorItem ? doctorItem.ghlbId : ''
    }
  }
}
const onChargeSuccess = async (chargeData = {}) => {
  chargeLoading.value = true
  registerState.value.isChargeInformationcard = registerState.value.xxkf ? 1 : 0
  registerState.value.isChargeMedicalbook = registerState.value.blbf ? 1 : 0
  const { code, msg, jzbhs, pjhm } = await post(
    '/outp/mzdj/doRegister',
    {
      ghfybh: getSystemConfig('NAVYHIS_MODE_REGISTRATION_FEE_CODE'),
      zlfybh: getSystemConfig('NAVYHIS_MODE_CONSULTATION_FEE_CODE'),
      // ghfybh: 'YP000000490', //todo
      // zlfybh: 'YP000000491', //todo
      ...patientState.value,
      ...registerState.value,
      ...chargeData,
      ghlbid: patientState.value.ghlbid || registerState.value.ghlbid,
      dictOutpMatterId: '',
      miFlag: 0,
      czfz: registerState.value?.czfz,
      fbyh: registerState.value.fbwc
      // vipno: memberId.value,
      // dyqzf: couponPrice.value, // 抵用券金额
      // dyqno: couponId.value // 抵用券id
    },
    { loading: true }
  )
  chargeLoading.value = false
  if (code !== 0) return message.error(msg || '挂号失败')
  message.success('挂号成功')
  getIsFirstRegistration()
  setTimeout(() => {
    onReset()
  }, 500)
  if (appStore.IS_PRINT) {
    if (systemConfig.value.isMergeRegisterFee) {
      onPrint(jzbhs)
    } else {
      onPrint(jzbhs, pjhm)
    }
  }
}
// 打印
const onPrint = (jzbhs = [], pjhm = []) => {
  if (registerState.value.ssje) {
    if (jzbhs.length > 0) {
      jzbhs.forEach(async (item, index) => {
        const { code, msg, data } = await post(systemConfig.value.isPrint, { jzbh: item, pjhm: pjhm[index] || null, sftfbs: 0 })
        if (code !== 0) return message.error(msg || '打印失败')
        window.openExe?.rpt(data) //调用winform打印
      })
    }
  } else {
    if (systemConfig.value.isBill) {
      if (jzbhs.length > 0) {
        jzbhs.forEach(async (item, index) => {
          const { code, msg, data } = await post(systemConfig.value.isPrint, { jzbh: item, pjhm: pjhm[index] || null, sftfbs: 0 })
          if (code !== 0) return message.error(msg)
          window.openExe?.rpt(data) //调用winform打印
        })
      }
    }
  }
}

// 判断是否是第一次挂号
const getIsFirstRegistration = async () => {
  if (systemConfig.value.isLabel) {
    const { code, data, msg } = await get('/common/patient/isFirstRegistration?br_id=' + patientState.value?.brId)
    if (code !== 0) return message.error(msg)
    data && onPrintLabel()
  }
  onReset()
}

// 打印客户标签
const onPrintLabel = async () => {
  const { code, msg, data } = await post('/outp/outPrint/getMedicalRecordLabelPrint', { brId: patientState.value?.brId })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

const savePatientInfo = async () => {
  const idCard = patientState.value.brSfz
  if (patientState.value.brZjlx && patientState.value.brZjlx === '身份证') {
    if (idCard && idCard.length) {
      const { code: codeZjh, msg: msgZjh } = await post('/common/util/getCsrq', { sfzhm: idCard })
      if (codeZjh !== 0) return message.error(msgZjh || '身份证有误')
    }
  }
  if (patientState.value.isBrBlkh && !patientState.value.brBlkh) {
    return message.error('请填写病历号')
  }
  if (patientState.value.jksy !== 0) {
    patientState.value.jksy = patientState.value?.brId ? 2 : 1
  }
  // 按断年龄是否为0，
  if (patientState.value.brAge === '0') {
    const isAgeConfirm = await cofirmModal({ title: '提示', content: '当前患者年龄为0,请确认是否真实?' })
    if (!isAgeConfirm) {
      return
    }
  }
  // 判断咨询师是否必填
  if (systemConfig.value.isCounselor && !patientState.value.brZxsName) {
    return message.error('请选择咨询师')
  }
  chargeLoading.value = true
  const { code, msg, data } = await post('/common/patient/savePatientInfo', patientState.value)
  chargeLoading.value = false
  if (code === 0) {
    patientState.value.brId = data
    onChargeSuccess()
  } else {
    if (patientState.value?.brId) return message.error(msg)
    const isConfirm = await cofirmModal({ title: '提示', content: msg })
    if (isConfirm) {
      patientState.value.jksy = 0
      savePatientInfo()
    }
  }
}
const onReset = () => {
  // czfz: 0,
  registerState.value = { ghlbid: systemConfig.value.defaultCategoryId, czfz: 0, xxkf: false, blbf: false }
  registerState.value.ksdm = systemConfig.value.defaultDepartment
  registerState.value.oldKsdm = systemConfig.value.defaultDepartment
  registerState.value.ksdms = [systemConfig.value.defaultDepartment]
  patientState.value = { brXb: '男' }
  getDoctorList()
  patientInfoForm.value.getMedicalRule()
}
// 判断必填项
// const isCompleted = computed(() => {
//   return registerState.value.ksdm && patientState.value.brName && patientState.value.brAge && systemConfig.value.isCounselor && patientState.value.brZxsName
// })
const isCompleted = computed(() => {
  const baseStatus = registerState.value.ksdm && patientState.value.brName && patientState.value.brAge
  return systemConfig.value.isCounselor ? baseStatus && patientState.value.brZxsName : baseStatus
})
watch(
  () => patientState.value.ghlbid,
  (val) => {
    onSelectDepartment(registerState.value.ksdm)
    if (val) {
      registerState.value.ghlbid = patientState.value.ghlbid
    } else {
      registerState.value.ghlbid = systemConfig.value.defaultCategoryId
    }
  }
)

const route = useRoute()
const dictMatterId = ref('') // 就诊事项id

//获取患者信息
const getPatientInfo = async () => {
  dictMatterId.value = route.query?.dictOutpMatterId
  if (route.query.id) {
    const { code, data = {} } = await get('/common/patient/getPatientInfo?br_id=' + route.query.id)
    if (code !== 0) return message.error('获取患者信息失败')
    patientState.value = { ...patientState.value, ...data } // yylsh: userInfoStore.patientInfo?.yylsh
    registerState.value.czfz = data.czfz ?? 0
    registerState.value.chargeStandardId = data.chargeStandardId
    registerState.value.ghlbid = data.ghlbid || systemConfig.value.defaultCategoryId
    patientState.value.jksy = 2
    if (data.yylsh) {
      registerState.value.ksdm = data.ksdm
      registerState.value.ksdms = [data.ksdm]
      registerState.value.memo = data.yymemo
      getDoctorList()
    }
  }
}
const systemConfig = ref({})
onMounted(async () => {
  await getDepartmentList()
  systemConfig.value = {
    defaultDepartment: getSystemConfig('REGISTER_DEFAULT_DEPT_CODE'), //默认挂号科室编号
    defaultCategoryId: getSystemConfig('REGISTER_DEFAULT_CATEGORY_CODE'), //默认挂号类别编号
    isHistoryList: getSystemConfig('REGISTER_FORM_SHOW_HISTORY') === '1', //是否显示历史记录1显示0不显示
    isAssistance: getSystemConfig('IS_SHOW_REGISTER_FORM_DOCTOR_ASSISTANT ') === '1', // 是否在挂号登记页显示医助
    isLabel: getSystemConfig('IS_REGISTER_AUTO_PRINT_PATIENT_LABEL') === '1', // 0：不打印|1：自动打印
    isBill: getSystemConfig('PRINT_BILL_WHEN_FEE_IS_ZERO') === '1', // 费用为0时判断是否打印 0：不打印 1：打印
    isCounselor: getSystemConfig('IS_REQUIRED_CONSULTANT') === '1', //是否咨询师必填
    isPrint: getSystemConfig('REGISTRATION_FORM_PRINT_MODE') === '2' ? '/outp/outPrint/getRegistrationPrint' : '/outp/outPrint/getRegistrationBillPrint' // 0：通用|1：上海黑马|2：茗视光
  }
  getPatientInfo()
  registerState.value.ghlbid = systemConfig.value.defaultCategoryId || registerState.value.ghlbid
  registerState.value.ksdm = systemConfig.value.defaultDepartment || departmentList.value[0]?.ksdm
  registerState.value.oldKsdm = systemConfig.value.defaultDepartment || departmentList.value[0]?.ksdm || registerState.value.oldKsdm
  registerState.value.ksdms = systemConfig.value.defaultDepartment ? [systemConfig.value.defaultDepartment] : [departmentList.value[0]?.ksdm]
})
//扫码
const onScanCode = async () => {
  setTimeout(async () => {
    if (patientState.value.brId) {
      const { code, data, msg } = await post('/outp/mzdj/getPatientRegistrationSign', { brId: patientState.value?.brId })
      if (code !== 0) return message.error(msg)
      if (data) {
        rowData.value = data
        signOpen.value = true
      }
    }
  }, 1000)
}
const onSuccessSignIn = () => {
  if (systemConfig.value.isMergeRegisterFee) {
    onPrint([rowData.value.jzbh])
  } else {
    onPrint([rowData.value.jzbh], [rowData.value.pjhm])
  }
}
</script>
<style lang="less" scoped>
.border-heavy {
  border-color: var(--border-heavy-color);
}

:deep(.ant-radio-button-wrapper) {
  flex: 1;
  color: var(--primary-color);
  text-align: center;
  border-color: var(--primary-color);
  &::before {
    background-color: var(--primary-color);
  }
}
/* For demo */
:deep(.slick-slide) {
  padding-right: 50px;
  padding-left: 50px;
  overflow: hidden;
  text-align: center;
}
:deep(.slick-arrow:before) {
  display: none;
}
.cost-type {
  :deep(.ant-form-item-required) {
    padding-top: 7px;
  }
}
:deep(.ant-card-body) {
  display: flex;
  flex-direction: column;
}
</style>
